const router = require('koa-router')();
const guacdConnect = require('../util/guacdConnect')
const CryptoJS = require('crypto-js')

router.post('/getToken',async (ctx) => {
  var remoteInfo = ctx.request.body;
  //var info = JSON.parse(JSON.stringify(ctx.request.body))
  console.log(remoteInfo.routeInfo.connection.settings.password)
  //await console.log(aesUtildecrypt(remoteInfo.routeInfo.connection.settings.password))
  remoteInfo.routeInfo.connection.settings.password = aesUtildecrypt(remoteInfo.routeInfo.connection.settings.password)
  //var password = aesUtildecrypt(remoteInfo.routeInfo.connection.settings.password)
 // info.routeInfo.connection.settings.password = aesUtildecrypt(info.routeInfo.connection.settings.password);
 // console.log(password)
  //await console.log(aesUtildecrypt(remoteInfo.routeInfo.connection.settings.password))
  ctx.response.body = guacdConnect.encrypt(remoteInfo.routeInfo)
});

function aesUtildecrypt(word) {
  const key = CryptoJS.enc.Utf8.parse('bhyh123456789123')
  const ivHex = CryptoJS.enc.Utf8.parse("ahyh123456789123")
  var encryptedHexStr = CryptoJS.enc.Hex.parse(word);
  var encryptedBase64Str = CryptoJS.enc.Base64.stringify(encryptedHexStr);
  var decryptedData = CryptoJS.AES.decrypt(encryptedBase64Str, key, {
    iv: ivHex,
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.Pkcs7
  });
  return decryptedData.toString(CryptoJS.enc.Utf8);


  // let decrypt = CryptoJS.AES.decrypt(word, key,
  //   {
  //     mode: CryptoJS.mode.ECB,
  //     padding: CryptoJS.pad.ZeroPadding,
  //     //padding: CryptoJS.pad.Pkcs7,
  //   },
  // )
  // let decString = CryptoJS.enc.Utf8.stringify(decrypt).toString();
  // return decString
}

module.exports = router;
